package phone.qyg.com.qyg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.TransformController;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import phone.qyg.com.qyg.MainActivity;
import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Third;
import phone.qyg.com.qyg.utils.AppHttpRequest;


/**
 * 作者：lblbh on 2017/5/18 17:00
 * 邮箱：lanbuhan@163.com
 * 功能：注册用户
 */
@ContentView(R.layout.third_two)
public class ThirdTwoActivity extends BaseActivity implements TextWatcher {
    private String botoom_title = "注册登录蒙享动即表示您同意«<font color='#00a3ea'>蒙享动用户协议</font>»";
    private String REG_NORMAL = "0" ;
    private String REG_OTHER = "1" ;
    private String reg_type = REG_NORMAL;//默认普通注册
    private int VERIFICATIONCONTENTSTR_SIZE = 6;//验证码的长度
    int i = 60;

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.submit)
    TextView submit;

    @ViewInject(R.id.verification_code)
    TextView verification_code;

    @ViewInject(R.id.regis_botton)
    TextView regis_botton;

    @ViewInject(R.id.phone)
    EditText phone;

    @ViewInject(R.id.code)
    EditText code;

    @ViewInject(R.id.one_pass)
    EditText one_pass;

    Third third;

    @Event(value = {R.id.back,R.id.regis_botton,R.id.verification_code,R.id.submit})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.verification_code:
                //获取验证码
                String phoneNums = phone.getText().toString();
                // 1. 通过规则判断手机号
                if (!judgePhoneNums(phoneNums)) {
                    return;
                }
                // 2.发送短信验证码
                updateVerification(phoneNums);
                // 3.倒计时
                verification_code.setClickable(false);
                verification_code.setText("重新发送("+i+")");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (; i > 0; i--) {
                            handler.sendEmptyMessage(-9);
                            if (i <= 0) {
                                break;
                            }
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        handler.sendEmptyMessage(-8);
                    }
                }).start();
                break;
            case R.id.submit:
                String phoneStr = phone.getText().toString().trim();
                String codeStr = code.getText().toString().trim();
                String onePassStr = one_pass.getText().toString().trim();

                int length = onePassStr.length();
                if(length<6 || length>16){
                    PromptManager.showToast(R.string.password_number_hint);
                    return;
                }

                if(!CommonUtil.isPassNO(onePassStr)){
                    PromptManager.showToast(R.string.pass_format_hint);
                    return;
                }

                if(isRequestStr(phoneStr)&&isRequestStr(codeStr)&&isRequestStr(onePassStr)){
                    if(!judgePhoneNums(phoneStr)){
                        //不合法手机号码
                        PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
                    }else{
                        //TODO 网络请求 现在短信认证还没有接通
                        //phone
                        mapKeys.put(AppHttpKey.MOBILE,phoneStr);
                        mapKeys.put(AppHttpKey.PASSWORD,onePassStr);
                        mapKeys.put(AppHttpKey.MOBILE_CODE,codeStr);
                        mapKeys.put(AppHttpKey.REG_TYPE,reg_type);
                        third.mobile = phoneStr;
                        third.login_name = phoneStr;
                        third.password = onePassStr;
                        third.mobile_code = codeStr;

                        String dataValue = JSON.toJSONString(third);
                        mapKeys.put(AppHttpKey.DATA,dataValue);

                        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.THIRD_LOGIN_BIND,
                                mapKeys,
                                new MyCallBack<String>(){
                                    @Override
                                    public void onSuccess(String result) {
                                        super.onSuccess(result);
                                        if(JSONTool.isStatus(result)){
                                            loginSucess(result);
                                        }else{
                                            //message
                                            PromptManager.showToast(JSONTool.errorHint(result));
//                                            PromptManager.showToast(JSONTool.requestJSONfindName(result,JSONTool.Enum.MESSAGE));
                                        }
                                    }
                                });


                    }
                }else{
                    PromptManager.showToast(R.string.phone_password_no);
                }
                break;
        }
    }

    /**
     * 登录成功
     * @param result
     */
    private void loginSucess(String result){

        SharePrefUtil.saveString(SharePrefUtil.KEY.APP_USER, JSONTool.requestJSONStringKey(result, JSONTool.Enum.DATA));

        Intent intent = new Intent(ApplicationConfig.APP_QX_LOGIN);
        intent.putExtra(TransformController.ChangeKEY.INTENT_KEY,result);
        LocalBroadcastManager.getInstance(QXApplication.getContext()).sendBroadcast(intent);

        ThirdTwoActivity.this.finish();
        TransformController.transformController(QXApplication.getContext(), MainActivity.class);
    }


    private void updateVerification(String phoneNums){
        if (!judgePhoneNums(phoneNums)) {
            PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
            return;
        }

        //TODO 向服务传递申请验证码请求
        mapKeys.put(AppHttpKey.MOBILE,phoneNums);
        AppHttpRequest.httpRequestDefalut(ApplicationConfig.SEND_SMS,
                mapKeys,
                new AppHttpRequest.OnAppHttpListener() {
                    @Override
                    public void onAppHttpState(boolean isState, String result) {
                        if(isState){
                            PromptManager.showToast(JSONTool.errorHint(result));
                        }
                    }
                });
    }


    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (CommonUtil.isMatchLength(phoneNums, 11)
                && CommonUtil.isMobileNO(phoneNums)) {
            return true;
        }
        PromptManager.showToast(R.string.mobile_phone_format_is_wrong);
        return false;
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                verification_code.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                verification_code.setText("获取验证码");
                verification_code.setClickable(true);
                i = 60;
            }
        }
    };



    @Override
    public void initSucessView() {
        third = (Third) getTransModels();
    }
    @Override
    public void initData(Bundle savedInstanceState) {}
    @Override
    public void initViewHandler() {
        textViewHTTPText(regis_botton,botoom_title);
        phone.addTextChangedListener(this);
        code.addTextChangedListener(this);
        one_pass.addTextChangedListener(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        submit.setEnabled(false);
        submit.setBackgroundResource(R.drawable.ash_btn_frame);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String phoneStr = getEditToString(phone);
        String codeStr = getEditToString(code);
        String onePassStr = getEditToString(one_pass);

        if(isRequestStr(phoneStr)&&isRequestStr(codeStr)&&isRequestStr(onePassStr)){
            submit.setEnabled(true);
            submit.setBackgroundResource(R.drawable.blue_btn_frame);
        }else{
            submit.setEnabled(false);
            submit.setBackgroundResource(R.drawable.ash_btn_frame);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
